// 全局请求路径，也就是后端的请求基准路径
import {
	baseApi
} from "@/config.js";
import utils from "./utils";
// 同时发送异步代码的次数，防止一次点击中有多次请求，用于处理
let ajaxTimes = 0;
const defaultHeader = {
	'content-type': 'multipart/form-data;charset=UTF-8',
	withCredentials: true,
	crossDomain: true
}

// 封装请求方法，并向外暴露该方法
const myHttp = (options) => {
	// 解构请求头参数
	let header = {};
	if (options.header) {
		header = {
			...defaultHeader,
			...options.header
		};
	}

	let token = uni.getStorageSync('token')
	// token =
	// 	"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTcyMDcwMDQ2MywianRpIjoiYzBhNDcwMGItZWYxMC00YmExLWI5MzItYTkwOWIwZDA1NWVhIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6eyJpZCI6MjAwMiwibmFtZSI6Ilx1OWE2Y1x1NTE0Ylx1OWE4YSJ9LCJuYmYiOjE3MjA3MDA0NjMsImV4cCI6MTcyMTMwNTI2M30.m-VLjZJ3frRHFI4JRTA8Mdt_PzZIjvr6WkLMAfBGyqo"
	if (token) {
		header['Authorization'] = `Bearer ${token}`
	}
	if (ajaxTimes == 0 && !options.hideLoad) {
		// NProgress.start()
		uni.showLoading({
			title: "加载中",
			mask: true,
		});
	}
	ajaxTimes++;
	// 显示加载中 效果
	// console.log("ajaxTimes------",ajaxTimes)

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseApi + options.url,
			method: options.method || 'get',
			data: options.data || options.params || {},
			header,
			success: (res) => {
				uni.stopPullDownRefresh()
				if (res.statusCode == 200 && res.data.code == 200) {
					resolve({
						data: res.data.data
					})
				} else {
					switch (res.statusCode) {
						case 401:
							uni.showToast({
								title: res.data.msg || '获取登录信息失败，请退出重新登录',
								icon: 'none',
								duration: 2000
							});

							uni.removeStorageSync('token');

							let routes = getCurrentPages() || [];
							let currentRoute = routes[routes.length - 1]
							let loginPath = "pages/login/index";

							console.log("currentRoute", currentRoute)
							console.log("loginPath", loginPath)

							if (currentRoute != loginPath) {
								uni.reLaunch({
									url: '/' + loginPath,
								})
							}
							break
						default:
							setTimeout(function() {
								uni.showToast({
									title: res && res.data.msg || '请求失败！',
									icon: 'none',
									duration: 2000
								});
							}, 10)
					}
					reject(res.data)
				}
			},
			fail: (error) => {
				setTimeout(function() {
					console.log(error)
					// console.log(error)
					uni.showToast({
						title: error && error.msg || '网络繁忙，请稍后再试',
						icon: 'none',
						duration: 2000
					});
				}, 100)
				reject(error)
			},
			// 完成之后关闭加载效果
			complete: () => {
				ajaxTimes--;
				// console.log("ajaxTimes======>>",ajaxTimes)
				if (ajaxTimes === 0 && !options.hideLoad) {
					//  关闭正在等待的图标
					uni.hideLoading();
				}
			}
		})
	})
}
export default myHttp;

/**
 * 上传文件
 * @param {Object} tempFilePath uni文件路径
 */
export function saveFile(tempFilePath) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseApi + "file",
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
			},
			filePath: newFillPath,
			name: 'file',
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					let resData = JSON.parse(uploadFileRes.data)
					resolve(resData)
				} else {
					reject(err)
				}
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
};